package com.best.lrc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LrcHandle {
	private List mWords = new ArrayList();   //歌词
	private List mTimeList = new ArrayList();  //歌词时间
	
	
	/**
	 * 处理歌词文件
	 * @param path
	 */
	public void readLRC(String path){
		File file = new File(path);
		try { 
			FileInputStream fileInputStream = new FileInputStream(file);
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
			BufferedReader bufferReader = new BufferedReader(inputStreamReader);
			String string = "";
			while ((string = bufferReader.readLine()) != null) {
				//addTimeToList(string);
                if ((string.indexOf("[ar:") != -1) || (string.indexOf("[ti:") != -1)
                        || (string.indexOf("[by:") != -1)) {
                	string = string.substring(string.indexOf(":") + 1, string.indexOf("]"));
                } else {
                    String ss = string.substring(string.indexOf("["), string.indexOf("]") + 1);
                    string = string.replace(ss, "");
                }
                mWords.add(string);
				
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			mWords.add("没有歌词文件，去下载吧！");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			mWords.add("木有读取到歌词");
		}
		
	}
	
	 public List getWords() {
	        return mWords;
	   }

	    public List getTime() {
	        return mTimeList;
	    }

	    // 分离出时间
	    private int timeHandler(String string) {
	       string = string.replace(".", ":");
	       String timeData[] = string.split(":");
	// 分离出分、秒并转换为整型
	        int minute = Integer.parseInt(timeData[0]);
	        int second = Integer.parseInt(timeData[1]);
	        int millisecond = Integer.parseInt(timeData[2]);

	        // 计算上一行与下一行的时间转换为毫秒数
	        int currentTime = (minute * 60 + second) * 1000 + millisecond * 10;

	        return currentTime;
	    }
	
	/** 
	 * 添加时间，使歌词时间与歌曲时间同步
	 * @param s
	 */
	public void addTimeToList(String s){
		Matcher matcher = Pattern.compile(
                "\\[\\d{1,2}:\\d{1,2}([\\.:]\\d{1,2})?\\]").matcher(s);
        if (matcher.find()) {
            String str = matcher.group();
            mTimeList.add(new LrcHandle().timeHandler(str.substring(1,str.length() - 1)));
        }

	}
}
